<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <style>
        .laytable-cell-customization {
            text-align: center;
            height: auto !important;
            white-space: normal;
            overflow: visible;
            text-overflow: inherit;
            word-break: break-all;
        }

        .layui-table img {
            max-width: 300px;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">标题</label>
                            <div class="layui-input-inline">
                                <input type="text" name="title" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">创建时间</label>
                            <div class="layui-input-inline">
                                <input type="text" name="dateRange" id="dateRange" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除</button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="imgTemp">
            {{# if(d.image != "" && d.image != null){ }}
            <img src="{{d.image}}" style="width: 100%;height: 45px"/>
            {{# } }}
        </script>

        <script type="text/html" id="currentTableBar">
            {{# if(d.top!=0){ }}
            <a class="layui-btn layui-btn-warm layui-btn-sm" lay-event="cancelIsTop">取消</a>
            {{#  }else{ }}
            <a class="layui-btn layui-btn-normal layui-btn-sm" lay-event="isTop">置顶</a>
            {{#  } }}
            {{# if(d.status == '0'){ }}
            <a class="layui-btn layui-btn-warm layui-btn-sm" lay-event="down">下架</a>
            {{#  }else{ }}
            <a class="layui-btn layui-btn-normal layui-btn-sm" lay-event="shelf">发布</a>
            {{#  } }}
        </script>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table','laydate'], function () {
        var $ = layui.jquery,
            form = layui.form,
            laydate = layui.laydate,
            table = layui.table;

        //执行一个laydate实例
        laydate.render({
            elem: '#dateRange', //指定元素
            max: 0, // 限制最大值为当前日期
            type: 'date',
            range: true, //开启范围选择
        });

        table.render({
            elem: '#currentTableId',
            url: '/article/page/list',
            method: 'POST',
            contentType: 'application/json',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", fixed: 'left', style: 'height:60px;'},
                {
                    field: 'numbering', title: '序号', width: 60, align: 'center', templet: function (d) {
                        return d.LAY_INDEX; //返回序号
                    }
                },
                {
                    field: 'image', title: '缩略图', align: 'center', templet: '#imgTemp',
                    style: 'height:60px;',
                    width: 80,
                },
                {field: 'title', title: '文章标题', align: 'center'},
                {field: 'id', title: '文章编号', align: 'center'},
                {field: 'url', title: '跳转地址', align: 'center'},
                {field: 'createTime', title: '添加时间', sort: true, align: 'center'},
                {
                    title: '操作',
                    toolbar: '#currentTableBar',
                    fixed: 'right',
                    width: 140,
                    align: 'center',
                    style: 'height:60px;'
                }
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            response: { //定义后端 json 格式，详细参见官方文档
                statusName: 'code', //状态字段名称
                statusCode: '200', //状态字段成功值
                msgName: 'msg', //消息字段
                countName: 'total', //总数字段
                dataName: 'rows' //数据字段
            },
            done: function (res, curr, count) {//表格渲染完成的回调函数
                // 给指定的列加上css样式
                let colsList = this.cols[0];
                myClos = colsList;
                for (let cols of colsList) {
                    if (cols.field === 'image' || cols.title === '操作') {
                        // 添加样式
                        let classStr = ".laytable-cell-1-" + cols.key;
                        $(classStr).addClass('laytable-cell-customization')//
                    }
                }
            }
        });

        // 监听表格排序事件
        table.on('sort(currentTableFilter)', function (obj) {
            for (let cols of myClos) {
                if (cols.field === 'image' || cols.title === '操作') {
                    // 添加样式
                    let classStr = ".laytable-cell-1-" + cols.key;
                    $(classStr).addClass('laytable-cell-customization')//
                }
            }
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            let dataRangeList = data.field.dateRange.split(` - `)
            let dataRange = {}
            if (dataRangeList.length === 2) {
                dataRange = {
                    'startDate': dataRangeList[0],
                    'endDate': dataRangeList[1]
                }
            }
            data.field.dateRange = JSON.stringify(dataRange);
            // 执行搜索重载
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: data.field
            }, 'data');

            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                layer.open({
                    title: '添加文章',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: './add.html',
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                let checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data.length > 0) {
                    layer.confirm('确定删除所选文章吗', function (index) {
                        let idList = []
                        for (const i in data) {
                            idList.push(data[i].id);
                        }
                        $.ajax({
                            type: "post",
                            url: '/article/delete',
                            data: JSON.stringify(idList),
                            dataType: 'json',
                            contentType: 'application/json',
                            success: function (req) {
                                if (req.code == 200) {
                                    layer.msg("已删除");
                                    reloadTable();
                                } else {
                                    layer.msg("删除失败");
                                }
                            },
                            error: function (e) {
                                layer.msg("删除失败");
                            }
                        })
                        layer.close(index);
                    });
                } else {
                    layer.alert('请至少选中一行数据');
                }
            }
        });

        // 监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'isTop') {
                layer.confirm('确定置顶所选文章吗！', function (index) {
                    $.ajax({
                        type: "POST",
                        url: '/article/top/' + data.id,
                        dataType: 'json',
                        contentType: 'application/json',
                        success: function (req) {
                            if (req.code == 200) {
                                layer.msg("已置顶");
                                reloadTable();
                            } else {
                                layer.msg("出错啦");
                            }
                            layer.close(index);
                        },
                        error: function (e) {
                            layer.msg("出错啦");
                            layer.close(index);
                        }
                    })
                });
            } else if (obj.event === 'cancelIsTop') {
                layer.confirm('确定取消置顶所选文章吗!', function (index) {
                    $.ajax({
                        type: "POST",
                        url: '/article/top/cancel/' + data.id,
                        dataType: 'json',
                        contentType: 'application/json',
                        success: function (req) {
                            if (req.code == 200) {
                                layer.msg("已取消");
                                reloadTable();
                            } else {
                                layer.msg("出错啦");
                            }
                            layer.close(index);
                        },
                        error: function (e) {
                            layer.msg("出错啦");
                            layer.close(index);
                        }
                    })
                });
            } else if (obj.event === 'down') {
                layer.confirm('确定下架所选文章吗!', function (index) {
                    $.ajax({
                        type: "POST",
                        url: '/article/down/' + data.id,
                        dataType: 'json',
                        contentType: 'application/json',
                        success: function (req) {
                            if (req.code == 200) {
                                layer.msg(data.title + "已下架");
                                reloadTable();
                            } else {
                                layer.msg("出错啦");
                            }
                            layer.close(index);
                        },
                        error: function (e) {
                            layer.msg("出错啦");
                            layer.close(index);
                        }
                    })
                });
            } else if (obj.event === 'shelf') {
                layer.confirm('确定发布所选文章吗?', function (index) {
                    $.ajax({
                        type: "POST",
                        url: '/article/shelf/' + data.id,
                        dataType: 'json',
                        contentType: 'application/json',
                        success: function (req) {
                            if (req.code == 200) {
                                layer.msg("已发布");
                                reloadTable();
                            } else {
                                layer.msg("出错啦");
                            }
                            layer.close(index);
                        },
                        error: function (e) {
                            layer.msg("出错啦");
                            layer.close(index);
                        }
                    })
                });
            }
        });

        table.on('rowDouble(currentTableFilter)', function (obj) {
            const rowData = obj?.data;
            if (rowData !== void 0 && rowData !== null) {
                layer.open({
                    title: '编辑文章',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: './edit.html?id=' + rowData.id,
                    end: function () {
                        //关闭弹框后触发
                        reloadTable();
                    }
                });
            } else {
                layer.msg("数据异常，请重新尝试");
            }
        });

    });

    /**
     * 重载表格数据
     */
    function reloadTable() {
        layui.use(['table'], function () {
            let table = layui.table;
            table.reload('currentTableId', {
                url: '/article/page/list'
            });
        })
    }
</script>

</body>
</html>
